<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 11:18
 */

namespace Modules\SmallApi\Service;

use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\UsersLevelRepository;
use HiCommon\Repository\AddressRepository;
use HiCommon\Repository\EquitiesRepository;
use HiCommon\Repository\UsersIntegralRepository;
use Modules\SmallApi\Service\CouponService;
class UserService extends BaseService
{

	/**
	 *	获取登录用户的信息
	 *	hinq 2019 08 30
	 *	使用场景【 个人中心 、 个人信息设置】
	 **/
	public function get_one(){
		try {
            //获取当前登录用户的信息
            if( empty( small_api_user_id() ) ){
                return ['state'=> 'no_user','msg'=>'用户未登录','data'=>[],'error'=>''];
            }
			$arr_where['field'] = ['id','nickname','head_img','birthday','integral','integral_all','status','phone','sex','realname','unique_token','small_openid'];
			$arr_list = UsersRepository::get_one( (int) small_api_user_id() ,(array) $arr_where );

			if( empty( $arr_list->first() ) ){  //判断结果集是否为空
				return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
			}
			if( $arr_list['status'] != 1 ){
				return ['state'=> 1,'msg'=>'该账户已冻结，请联系管理员','data'=>[],'error'=>''];
			}
			$arr_list['birthday'] = !empty( $arr_list['birthday'] ) ? date('Y-m-d',$arr_list['birthday']) : '';
			// $sex_list = ['1'=>'男' , '2'=>'女' , '3'=>'保密'];
			// $arr_list['sex'] = $sex_list[$arr_list['sex']];
        $arr_list['full_phone'] = $arr_list['phone'];
        $arr_list['phone'] = !empty( $arr_list['phone'] ) ? substr($arr_list['phone'] , 0, 3 ).'****'.substr($arr_list['phone'], -4) : '';

			//获取vip会员等级信息
			$temp_where['field'] = ['id','name','min_integral','max_integral'];
			$arr_user_level = UsersLevelRepository::get_all( (array) $temp_where );
			$level = [];
			foreach ($arr_user_level as $key => $value) {
				if( intval( $arr_list['integral_all'] ) >= $value['min_integral'] && $arr_list['integral_all'] <= $value['max_integral'] ){
					$level['id'] = $value['id'];
					$level['name'] = $value['name'];
				}
			}
			$arr_list['level'] = $level;
			return ['state' => 0, 'msg' => 'ok', 'data' => $arr_list, 'error' => ''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}


	/**
     *	更新用户的信息
     *	hinq 2019 08 30
     *	使用场景【 个人信息设置详情页】
     **/
    public function update_one( array $arrInput ){
    	try {
    	       
            if( empty( array_filter( $arrInput ) ) ){
                return ['state'=> 1,'msg'=>'参数不能为空','data'=>[],'error'=>''];
            }
			//如果有手机号码  验证手机号码格式
			if( !empty( $arrInput['phone'] ) ){
				if( !preg_match("/^1[3456789]{1}\d{9}$/",$arrInput['phone'])){
		            return ['state'=> 1,'msg'=>'手机号码格式不正确','data'=>[],'error'=>''];
				}
                if( empty( $arrInput['code'] ) ){
                    return ['state'=> 1,'msg'=>'请填写短信验证码','data'=>[],'error'=>''];
                }
                //验证手机号码+验证码是否输入成功   有用不可删除
                $check = check_phone_code( $arrInput['phone'] , $arrInput['code'] );
                if( $check['state'] != 0){
                    return $check;
                }
                unset( $arrInput['code'] );
			}
			//如果有修改性别，验证参数是否合法
			if( !empty( $arrInput['sex'] ) ){
				if( !in_array( $arrInput['sex'] , [1,2,3] ) ){
		            return ['state'=> 1,'msg'=>'性别参数错误','data'=>[],'error'=>''];
				}
			}
            //如果修改的是生日信息
            if( !empty( $arrInput['birthday'] ) ){
                $arrInput['birthday'] = strtotime( $arrInput['birthday'] );
            }

            $arrInput['id'] = small_api_user_id();
			$res = UsersRepository::edit_one( (array) $arrInput );
			$result = hi_check_res($res,'edit_one');
		        if ($result['state'] != 0) {
		            return ['state'=> 1,'msg'=>'信息更新失败','data'=>[],'error'=>''];
		        }
		        return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
    	} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }



    /**
     *	获取登录用户的收货地址
     *
     *  hinq 2019 08 30
     **/
    public function get_address_list(){
    	try {
            $arr_where = ['user_id'=>small_api_user_id() , 'status'=>1];
            $arr_option['field'] = ['id','username','phone','province','city','area','address','is_defaule','created_at','status'];
    		$res = AddressRepository::get_list_by_where( (array) $arr_where , (array) $arr_option );
			return ['state'=> 0,'msg'=>'','data'=>$res,'error'=>''];
    	} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }



    /**
     *  验证收货地址
     *  hinq 2019 10 15
     **/
    public function check_data( array $arrInput ){
        if( empty( $arrInput['username'] ) ){
            return ['state'=> 1,'msg'=>'收货人姓名不能为空','data'=>[],'error'=>''];
        }
        if( empty( $arrInput['phone'] ) ){
            return ['state'=> 1,'msg'=>'收货人手机号码不能为空','data'=>[],'error'=>''];
        }
        if( empty( $arrInput['region'] ) ){
            return ['state'=> 1,'msg'=>'请选择省市区','data'=>[],'error'=>''];
        }

        $arrInput['province'] = $arrInput['region'][0];
        $arrInput['city'] = $arrInput['region'][1];
        $arrInput['area'] = $arrInput['region'][2];
        unset( $arrInput['region'] );
        if( empty( $arrInput['address'] ) ){
            return ['state'=> 1,'msg'=>'详细地址不能为空','data'=>[],'error'=>''];
        }
        if( mb_strlen( $arrInput['address'] ) > 50 ){
            return ['state'=> 1,'msg'=>'详细地址最多50个字符','data'=>[],'error'=>''];
        }
        return $arrInput;
    }



    /**
     *	添加收货地址
     *	hinq 2019 08 30
     *	使用场景【 收货地址管理】
     **/
    public function create_address( array $arrInput ){
    	\DB::beginTransaction();
    	try {
            $user_id = small_api_user_id();
            $data = self::check_data( (array) $arrInput );
            $data['user_id'] = $user_id;
            $res = true;
    		if( $data['is_defaule'] == 1 ){ //当前的数据需要设为默
    			//获取之前设置的默认数据
    			$arr_where['user_id'] = $user_id;
    			$arr_where['is_defaule'] = 1;
                $arr_option['is_defaule'] = 0;
                $res = AddressRepository::edit_one_where( (array) $arr_where , (array) $arr_option );
                if( $res == 0 ){   //有可能之前没有设置默认地址 返回值为0 影响后面判断 但是不能影响程序正常执行
                    $res = true;
                }
    		}
    		$res2 = AddressRepository::add_one( (array) $data );
    		if( $res2 && $res ){
                \DB::commit();
                return hello_success( 'ok');
            }
    		return hello_error('地址添加失败');
    	} catch (\Exception $exception) {
    		\DB::rollBack();
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *	获取指定的收货地址
     *	hinq 2019 08 30
     *	使用场景【 收货地址管理】
     **/
    public function get_one_address( int $nId ){
    	try{
    		if( empty( $nId ) ){
    			return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
    		}
    		$arr_where = [ 'user_id' => small_api_user_id() ,'status' => 1 ];  //当前登录者的id  防止随意传id获取别人的地址信息
            $arr_option['field'] = ['id','username','phone','province','city','area','address','is_defaule','created_at'];
    		$res = AddressRepository::get_one( (int) $nId , (array) $arr_where , (array) $arr_option );
            $res['region'] = [$res['province'],$res['city'],$res['area']];
    		$result = hi_check_res($res,'get_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'地址获取失败','data'=>[],'error'=>''];
	        }
	        return ['state'=> 0,'msg'=>'ok','data'=>$res,'error'=>''];
    	} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *	更新指定的收货地址信息
     *	hinq 2019 08 30
     *	使用场景【 收货地址管理】
     **/
    public function update_address( array $arrInput ){
    	\DB::beginTransaction();
    	try{
    		if( empty( $arrInput ) ){
    			return ['state'=> 1,'msg'=>'参数不能为空','data'=>[],'error'=>''];
    		}
            $data = self::check_data( (array) $arrInput );
    		//验证当前数据是否是登录者的地址信息
            $user_id = small_api_user_id();
    		$temp_where['user_id'] = $user_id;
            $temp_where['id'] = $data['id'];
            $temp_where['status'] = 1;
    		$count = AddressRepository::get_count_by_where( (array) $temp_where );
    		if( $count == 0 ){
    			return ['state'=> 1,'msg'=>'收货地址修改失败','data'=>[],'error'=>''];
    		}
            $res = true;
    		if( $data['is_defaule'] == 1 ){ //当前的数据需要设为默
    			//获取之前设置的默认数据
    			$arr_where['user_id'] = $user_id;
    			$arr_where['is_defaule'] = 1;
                //将之前设置的默认地址修改为非默认
                $arr_option['is_defaule'] = 0;
                $res = AddressRepository::edit_one_where( (array) $arr_where , (array) $arr_option );
                if( $res == 0 ){   //有可能之前没有设置默认地址 返回值为0 影响后面判断 但是不能影响程序正常执行
                    $res = true;
                }
    		}
    		$res2 = AddressRepository::edit_one( (array) $data );
    		if( $res2 && $res ){
                \DB::commit();
                return hello_success('ok');
            }
    		return hello_error('地址更新失败');
    	} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  删除指定的收货地址
     *  hinq 2019 08 30 
     *  使用场景【  删除地址 】 
     **/
    public function del_address( int $nId ){
        try{
            if( empty( $nId ) ){
                return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
            }
            $temp_where['user_id'] = small_api_user_id();
            $temp_where['id'] = $nId;
            $count = AddressRepository::get_count_by_where( (array) $temp_where );
            if( $count != 1 ){
                return ['state'=> 1,'msg'=>'删除失败','data'=>[],'error'=>''];
            }
            $arr_option['status'] = 2;
            //地址信息不能真删除  不然订单关联的收货地址信息就会查询不到
            $res = AddressRepository::edit_one_where( (array) $temp_where , (array) $arr_option );
            if( empty( $res ) ){
                return hello_error('删除失败');
            }
            return hello_success('ok');
        } catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }

    }


    /**
     *	获取所有的vip等级
     *	hinq 2019 09 02
     *	使用场景【个人中心 VIP会员】
     **/
    public function get_vip_list(){
    	//获取所有vip会员等级
        $temp_where['field'] = ['id','name','min_integral','max_integral','equities'];
    	$temp_where['order'] =[ 'key'=>'min_integral','value'=>'asc'];  //按积分大小排序
    	$arr_vip_list = UsersLevelRepository::get_all( (array) $temp_where );


    	//获取当前用户的信息
    	$arr_where['field'] = ['id','nickname','head_img','integral','integral_all'];
    	$uid = small_api_user_id();
		$arr_user_info = UsersRepository::get_one( (int) $uid ,(array) $arr_where );
		foreach ($arr_vip_list as $key => $value) {
			$arr_vip_list[$key]['checked'] = false;
            // 当前登录用户的累计积分总数        >=      会员等级设置的最小数       当前登录用户的累计积分总数 <= 会员等级最大数
			if( intval( $arr_user_info['integral_all']) >= $value['min_integral'] && intval( $arr_user_info['integral_all']) <= $value['max_integral'] ){
				$arr_vip_list[$key]['checked'] = true;
				$arr_user_info['level_name'] = $value['name'];
                $arr_user_info['level_max_integral'] = $value['max_integral'];
                $arr_user_info['level_id'] = $value['id'];
                $arr_user_info['level_equities_num'] = count( explode(',', $value['equities']) );
            }
            $arr_vip_list[$key]['equities'] = explode(',', $value['equities']);
		}
		//获取所有的权益数据
        $arr_where['field'] =[ 'id','name','img','remark'];
    	$arr_where['order'] =[ 'key'=>'id','value'=>'asc'];
		$arr_equities = EquitiesRepository::get_all( (array) $arr_where );
        foreach ($arr_vip_list as $k => $val) {
            if( $val['checked'] ){
                foreach ($arr_equities as $key => &$value) {
                    $value['img'] = oss_full_url( $value['img']);
                    if( in_array($value['id'], $val['equities']) ){
                        $value['selected'] = true;
                    }else{
                        $value['selected'] = false;
                    }
                }
            }
        }
    	$arr_list['vipList'] = $arr_vip_list;
    	$arr_list['userInfo'] = $arr_user_info;
    	$arr_list['equities'] = $arr_equities;
    	return ['state'=> 0,'msg'=>'ok','data'=>$arr_list,'error'=>''];	
    }


    // public function b64_upload_img( $file ){
       
    //     $fil = $file->getClientOriginalName();//图片路径
    //     $data = $file->move("img",$fil);//移动至框架图片文件夹
    // }

    /**
     *  修改用户的积分（添加、减少） 【给用户添加、扣除积分的唯一入口】
     *  积分兑换比  1:1  不足1积分的舍弃    给用户添加积分后 调用是否需要给用户发放会员等级升级礼包
     *  hinq 2019 09 24
     *  $arrInput['user_id']   int    用户id
     *  $arrInput['total_fee']   int   支付金额
     *  $arrInput['type']    int   1：增加积分   2：减扣积分
     *  $arrInput['order_id']     int  关联的订单id
     *  $arrInput['order_type']    int   订单类型   1：积分兑换   2：检测机构预约年检  3：维修店订单
     *  $arrInput['remarks']    string  备注   流水说明
     *  以上参数都是必填项
     *  接口位置 UserService::user_integral_change()
     **/
    public function user_integral_change( array $arrInput ){
        try{

            if( empty( $arrInput['total_fee'] ) && $arrInput['total_fee'] != 0 ){
                return ['state'=> 1,'msg'=>'积分不能为空','data'=>[],'error'=>'']; 
            }

            if( empty( $arrInput['type'] ) ){
                return ['state'=> 1,'msg'=>'请设置积分操作类型','data'=>[],'error'=>'']; 
            }

            if( empty( $arrInput['order_id'] ) ){
                return ['state'=> 1,'msg'=>'请设置关联订单','data'=>[],'error'=>'']; 
            }

            if( empty( $arrInput['order_type'] ) ){
                return ['state'=> 1,'msg'=>'请设置关联订单类型','data'=>[],'error'=>'']; 
            }

            if( empty( $arrInput['remarks'] ) ){
                return ['state'=> 1,'msg'=>'请设置备注信息','data'=>[],'error'=>'']; 
            }
            $arrInput['integral'] = $arrInput['total_fee'] * 100;
            $uid = $arrInput['user_id'];
            $arr_where = $arrInput;
            unset( $arr_where['remarks'] );
            unset( $arr_where['integral'] );
            unset( $arr_where['total_fee'] );
            $count = UsersIntegralRepository::get_count_by_where( (array) $arr_where );
            unset( $arr_where);
            if( $count >= 1 ){
                return ['state'=> 1,'msg'=>'该订单已评论','data'=>[],'error'=>'']; 
            } 
            //获取用户的积分信息
            $user_info = UsersRepository::get_one( (int) $uid , (array) ['field'=>['id','integral','integral_all','status']]);
            if( empty( $user_info->first() ) ){
                return ['state'=> 1,'msg'=>'获取用户信息失败','data'=>[],'error'=>'']; 
            }
            $user_info = $user_info->toArray();
            if( $user_info['status'] != 1 ){  
                return ['state'=> 1,'msg'=>'用户禁用，不可操作','data'=>[],'error'=>'']; 
            }
         
            //添加用户积分流水
            $data['user_id'] = $uid;
            $data['type'] = $arrInput['type'];
            $data['deduct'] = floor( $arrInput['integral'] );  //向下取整  1.23  1.95 都取1 小数部分都舍弃
            if( $arrInput['type'] == 1 ){
                //  操作后的积分   =   用户当前的积分    +  需要操作的积分
                $data['surplus'] = $user_info['integral'] +  floor( $arrInput['integral'] );
            }else{
                 //用户积分小于当前需要操作 的积分
                if( $user_info['integral'] < floor( $arrInput['integral'] ) ){
                    return ['state'=> 1,'msg'=>'当前积分操作有误，请核实','data'=>[],'error'=>''];
                }
                //  操作后的积分   =   用户当前的积分    -   需要操作的积分
                $data['surplus'] = $user_info['integral'] -  floor( $arrInput['integral'] ) ;
            }
            $data['order_id'] = $arrInput['order_id'];
            $data['order_type'] = $arrInput['order_type'];
            $data['remarks'] = $arrInput['remarks'];

            $res = UsersIntegralRepository::add_one( $data );
            if( $arrInput['type'] == 1 ){   //给用户添加积分
                $temp['integral'] = $user_info['integral'] + floor( $arrInput['integral'] );
                $temp['integral_all'] = $user_info['integral_all'] + floor( $arrInput['integral'] );
                $temp['id'] = $uid;
                $res2 = UsersRepository::edit_one( (array) $temp );
            }else{     //给用户扣除积分
                $res2 = UsersRepository::decrease_num( (int) $uid , 'integral' ,  floor( $arrInput['integral'] ) );
            }

            $result = hi_check_res($res2,'edit_one');
            if ($result['state'] != 0) {
                return ['state'=> 1,'msg'=>'操作失败','data'=>[],'error'=>''];
            }
            if( $arrInput['type'] == 1 ){  //添加积分
                //判断添加完积分后用户是否升级会员等级，并且发放会员等级礼包
                CouponService::send_upgrade_material_benefits( $uid );
            }
            return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
        } catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }





    /**
     *  手动给用户添加积分 （测试完后需要删除）
     *  hinq 2019 09 29 
     *  $arrInput['integral']   积分
     **/  
    public function chenge_user_integral( array $arrInput ){

            $uid = small_api_user_id();

            //获取用户的积分信息
            $user_info = UsersRepository::get_one( (int) $uid , (array) ['field'=>['id','integral','integral_all','status']]);

            //添加用户积分流水
            $data['user_id'] = $uid;
            $data['type'] = 1;
            $data['deduct'] = floor( $arrInput['integral'] );  //向下取整  1.23  1.95 都取1 小数部分都舍弃
            //  操作后的积分   =   用户当前的积分    +  需要操作的积分
            $data['surplus'] = $user_info['integral'] +  floor( $arrInput['integral'] );
            $data['order_id'] = 'CS'.time();
            $data['order_type'] = 4;
            $data['remarks'] = '手动给用户创建积分';

            $res = UsersIntegralRepository::add_one( $data );
            if (empty($res)) {
                return hello_error('评价失败');
            }
            $temp['integral'] = $user_info['integral'] + floor( $arrInput['integral'] );
            $temp['integral_all'] = $user_info['integral_all'] + floor( $arrInput['integral'] );
            $temp['id'] = $uid;
            $res2 = UsersRepository::edit_one( (array) $temp );
            CouponService::send_upgrade_material_benefits( $uid );
            if (empty($res2)) {
                return hello_error('评价失败');
            }
            return hello_success('添加成功');
    }



}